var express=require('express');
var Article=require('../modules/article.js')
var User=require('../modules/user.js')
var multiparty = require('multiparty'); 
var router = express.Router();
router.post('/editArticle',async(req,res)=>{
	console.log(req.body)
		await Article.insertMany([
			{
				name:req.body.name,
				content:req.body.content
			}
		])
	res.send({
		msg:'success'
	})
})
router.post('/getArticle',async(req,res)=>{
	let total=await Article.find()
	total=total.length
	// console.log(total)
	let currentPage=req.body.currentPage
	let pageSize=req.body.pageSize
	const obj=await Article.find().skip((currentPage-1)*pageSize).limit(pageSize)
	// console.log(obj)
	res.send({
		msg:'success',
		data:obj,
		total,
		currentPage
	})
})
router.post('/getArticleDetail',async(req,res)=>{
	const id=req.body.id
	let obj=await Article.find()
	obj=obj.filter(ele=>{
		return ele.id===id
	})
	// console.log(obj)
	res.send({
		msg:'success',
		data:obj
	})
})
router.post('/updateArticleDetail',async(req,res)=>{
	console.log(req.body)
	const id=req.body.id
	const name=req.body.name
	const content=req.body.content
	console.log(name,content)
	let obj=await Article.updateOne({_id:id},{name,content})
	// console.log(obj)
	res.send({
		msg:'success',
		data:obj
	})
})
router.post('/delArticle',async(req,res)=>{
	await new Promise((resolve,reject)=>{
		setTimeout(()=>{
			resolve()
		},5000)
	})
	console.log(req.body)
	
	const id=req.body.id
	let obj=await Article.deleteOne({_id:id})
	console.log(obj)
	let total=await Article.find()
	total=total.length
	let currentPage=req.body.currentPage
	let pageSize=req.body.pageSize
	const obj2=await Article.find().skip((currentPage-1)*pageSize).limit(pageSize)
	res.send({
		msg:'success',
		data:obj2,
		total
	})
})
router.post('/getUpload',async(req,res)=>{
	console.log(req)
	res.send({
		msg:'success'
	})
})
router.post('/doProductAdd',async(req,res)=>{

    //获取表单的数据 以及post过来的图片
	// console.log(req)
	// res.send('success')

    var form =await new multiparty.Form();

    form.uploadDir='upload'   //上传图片保存的地址     目录必须存在

    await form.parse(req, async(err, fields, files)=> {
		await User.deleteOne({
			   
		})
		console.log(files.file[0].path)
		await User.insertMany({
			avatar:files.file[0].path
		})
		res.send({
			msg:'success'
		})
        // var title=fields.title[0];
        // var price=fields.price[0];
        // var fee=fields.fee[0];
        // var description=fields.description[0];
        // var pic=files.pic[0].path;
        // console.log(pic);
    });
	
})
router.post('/getInit',async(req,res)=>{
	
	let obj=await User.find({
		
	})
	res.send({
		...obj
	})
})
module.exports =router